package com.ming.spring.servlet;

import com.ming.spring.annotation.HAutowired;
import com.ming.spring.annotation.HController;
import com.ming.spring.annotation.HRequestMapping;
import com.ming.spring.annotation.HService;
import org.springframework.util.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;


public class DispatcherServlet extends HttpServlet {
    /**
     * 属性配置文件
     */
    private Properties contextConfig = new Properties();
    private List<String> classNameList = new ArrayList<>();
    /**
     * ioc容器
     */
    Map<String, Object> iocMap = new HashMap<>();
    Map<String, Method> handlerMapping = new HashMap<String, Method>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("500 Exception Detail:\n" + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException {
        UUID uuid = UUID.randomUUID();
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replaceAll(contextPath, "").replaceAll("/+", "/");
        System.out.printf("uuid:%s,url:%s\n", uuid, url);

        // 处理器适配器适配
        if (!this.handlerMapping.containsKey(url)) {
            try {
                System.out.printf("uuid:%s,request 404\n", uuid);
                resp.getWriter().write("404");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Method method = this.handlerMapping.get(url);
        System.out.printf("uuid:%s,method:%s\n", uuid, method);

        // 获取该类的class类名
        String beanName = toLowerFirstCase(method.getDeclaringClass().getSimpleName());
        System.out.printf("uuid:%s,iocMap.get beanName(%s)\n", uuid, iocMap.get(beanName));

        // 获取方法,参数1,参数2
        method.invoke(iocMap.get(beanName), req, resp);
        System.out.printf("uuid:%s,method.invoke put\n", iocMap.get(beanName));
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        // 1. 加载配置文件
        doLoadConfig(servletConfig.getInitParameter("contextConfigLocation"));

        // 2. 扫描相关的类
        System.out.println("开始扫描配置路径");
        doScanner(contextConfig.getProperty("hw.framework.app.base_package"),"\t");
        System.out.println("结束扫描配置路径");

        // 3. 初始化IOC容器
        doInstance();

        // 4. 依赖注入
        doAutowired();

        // 5. 初始化HandlerMapping
        initHandlerMapping();
        System.out.println("spring framework is init.");

        // 6. 打印数据
        doTestPrintData();
    }

    /**
     * 1. 加载配置文件
     *
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        System.out.printf("开始加载配置文件:%s\n", contextConfigLocation);
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        // 保存在内存
        try {
            contextConfig.load(in);
            System.out.println("成功加载配置文件.");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.printf("结束加载配置文件:%s\n", contextConfigLocation);

    }

    /**
     * 2. 扫描相关的类
     *
     * @param scanPackage
     */
    private void doScanner(String scanPackage,String space) {
        System.out.printf("%s%s\n",space, scanPackage);

//        scanPackage = scanPackage.replaceAll("\\.", "/");
//        ClassLoader classLoader = this.getClass().getClassLoader();
//        URL url = classLoader.getResource("/"+scanPackage);
        URL resourcePath = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
//        String resourcePath = url.getPath().replace("%20", " ");

        if (null == resourcePath) {
            return;
        }
        File classPath = new File(resourcePath.getPath().replace("%20"," "));

        for (File file : Objects.requireNonNull(classPath.listFiles())) {
            // 目录递归处理
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName(),space+"\t");
            } else {
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                String className = (scanPackage + "." + file.getName()).replace(".class", "");
                // 保存类的全路径
                System.out.printf("%s%s\n",space+"\t", className);
                classNameList.add(className);
            }
        }


    }

    /**
     * 3. 初始化IOC容器,保存实例
     */
    private void doInstance() {
        System.out.println("开始初始化IOC容器");
        if (classNameList.isEmpty()) {
            return;
        }
        // 遍历类的全路径
        for (String className : classNameList) {
            try {
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(HController.class)) {
                    String beanName = toLowerFirstCase(clazz.getSimpleName());
                    Object instance = clazz.newInstance();

                    // IOC容器保存实例
                    iocMap.put(beanName, instance);
                    System.out.printf("     iocMap save %s,%s\n", beanName, instance);

                } else if (clazz.isAnnotationPresent(HService.class)) {
                    {
                        String beanName = toLowerFirstCase(clazz.getSimpleName());
                        // 注解是否包含自定义的名称
                        HService service = clazz.getAnnotation(HService.class);
                        if (!"".equals(service.value())) {
                            beanName = service.value();
                        }
                        // 创建实例
                        Object instance = clazz.newInstance();
                        iocMap.put(beanName, instance);
                        System.out.printf("     iocMap save %s,%s\n", beanName, instance);
                        for (Class<?> i : clazz.getInterfaces()) {
                            if (iocMap.containsKey(i.getName())) {
                                throw new RuntimeException("bean is Exist");
                            }
                            // 保存实例
                            iocMap.put(i.getName(), instance);
                            System.out.printf("     iocMap save %s,%s\n", beanName, instance);
                        }
                    }
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
        System.out.println("结束初始化IOC容器");

    }

    /**
     * 4. 依赖注入
     */
    private void doAutowired() {
        System.out.println("开始进行依赖注入");
        if(iocMap.isEmpty()){
            return;
        }
        // 遍历IOC容器
        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            // 判断实例是否需要注入
            for (Field field : fields) {
                if (!field.isAnnotationPresent(HAutowired.class)) {
                    continue;
                }
                // 获取注解对应的类
                HAutowired autowired = field.getAnnotation(HAutowired.class);
                String beanName = autowired.value().trim();

                // 获取注入的值
                if ("".equals(beanName)) {
                    beanName = field.getType().getName();
                }
                // 属性注入,处理封装
                field.setAccessible(true);

                try {
                    field.set(entry.getValue(), iocMap.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("结束进行依赖注入");
    }

    /**
     * 5. 初始化HandlerMapping
     */
    private void initHandlerMapping() {
        System.out.println("开始路径映射");
        if (iocMap.isEmpty()) {
            return;
        }
        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
            Class<?> clazz = entry.getValue().getClass();
            // 遍历Bean实例,如果不包含@Controller,过滤
            if(!clazz.isAnnotationPresent(HController.class)){
               continue;
            }
            // 类注解处理
            // Controller路径前缀
            String baseUrl = "";
            if (clazz.isAnnotationPresent(HRequestMapping.class)) {
                HRequestMapping requestMapping = clazz.getAnnotation(HRequestMapping.class);
                baseUrl = requestMapping.value();
            }

            // 方法注解处理
            // 获取controller类的所有方法
            for (Method method : clazz.getMethods()) {

                HRequestMapping requestMapping = method.getAnnotation(HRequestMapping.class);

                if(StringUtils.isEmpty(requestMapping)){
                    System.out.printf("\t路径映射:%s,%s\n",baseUrl,requestMapping);
                    continue;
                }
                System.out.printf("\t路径映射:%s,%s\n",baseUrl,requestMapping.method());
                String url = ("/"+baseUrl+"/"+requestMapping.value()).replaceAll("/+","/");
                handlerMapping.put(url,method);

            }

        }
        System.out.println("结束路径映射");
    }

    /**
     * 打印数据
     */
    private void doTestPrintData(){
        System.out.printf("propertyName %s\n",contextConfig.propertyNames());

        System.out.println("classNameList=>");
        for (String className : classNameList) {
            System.out.println("\t"+className);
        }
        System.out.println("iocMap=>");
        for (Map.Entry<String, Object> entry : iocMap.entrySet()) {
            System.out.println(entry);
        }
        System.out.println("handlerMapping=>");
        handlerMapping.forEach((key, value) -> System.out.printf("\t %s,%s \n", key, value));

        System.out.println("===启动成功===");

    }


    /**
     * 获取类的首字母小写的名称
     *
     * @param className
     * @return
     */
    private String toLowerFirstCase(String className) {
        char[] charArray = className.toCharArray();
        charArray[0] += 32;
        return String.valueOf(charArray);
    }

}